﻿using LibBinary.DataSource;
using LibBinary.FileData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LibBinary.FileDeclaration.Binary
{
    public class ArrayDeclaration : IFileDeclaration
    {
        private readonly ILengthProvider length;
        private readonly IFileDeclaration item;

        public ArrayDeclaration(ILengthProvider length, IFileDeclaration item)
        {
            this.length = length;
            this.item = item;
        }

        public AbstractFileData Read(BinaryFileSource src, AbstractFileData parentNode)
        {
            var ret = new ArrayData(parentNode);
            int len = length.GetLength(ret);
            AbstractFileData[] data = new AbstractFileData[len];
            for (int i = 0; i < len; ++i)
            {
                data[i] = item.Read(src, ret);
            }
            ret.Data = data;
            return ret;
        }

        public void Write(BinaryFileSource src, AbstractFileData data)
        {
            var cdata = data.As<ArrayData>();
            if (cdata == null)
            {
                throw new WritingFormatException("Wrong data type.");
            }
            foreach (var dataitem in cdata.Data)
            {
                item.Write(src, dataitem);
            }
        }
    }
}
